﻿using Rbac.Domain.Entity;
using Rbac.Domain.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Rbac.Domain.Impl
{
	public class RolePermissionRepository:IRolePermissionRepository
	{
		private readonly RbacContext db;
		public RolePermissionRepository(RbacContext db)
		{
			this.db = db;
		}
		/// <summary>
		/// 为角色分配权限
		/// </summary>
		/// <param name="roleId"></param>
		/// <param name="permissionIdList"></param>
		/// <returns></returns>
		public int DistributeRolePermissions(int roleId, List<int> permissionIdList)
		{
			if(permissionIdList.Count<=0)
			{
				return 0;
			}
			//最新的权限列表
			List<RolePermission> list = permissionIdList.Select(c => new RolePermission
			{
				RoleId=roleId,
				PermissionId=c
			}).ToList();
			//查询原有的权限列表
			var oldPermissions=db.RolePermissions.Where(c => c.RoleId == roleId);
			//移除原的权限的权限
			db.RolePermissions.RemoveRange(oldPermissions);

			//获取需要被移除的权限
			//var needDeleteList=oldPermissions.Except(list);//取差集
			//db.RolePermissions.RemoveRange(needDeleteList);
			//var needAddList=list.Except(oldPermissions);//新增的权限
			//db.RolePermissions.AddRange(needAddList);
			db.RolePermissions.AddRange(list);
			return db.SaveChanges();
		}
		/// <summary>
		/// 根据角色获取权限列表
		/// </summary>
		/// <param name="roleId"></param>
		/// <returns></returns>
		public List<Permission> GetPermissionsByRoleId(int roleId)
		{
			//根据角色id获取权限idlist
			var permissionIdList= db.RolePermissions.Where(c => c.RoleId == roleId).Select(c => c.PermissionId);
			//权限idlist去权限表中获取详细信息
			return db.Permissions.Where(c => permissionIdList.Contains(c.PermissionId)).ToList();
		}
	}
}
